/*
 * bomb_list.c
 *
 *  Created on: 28 Mars. 2013
 *      Author: Sandrine Soub and Benjamin Rambaud
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "SDL.h"
#include "SDL_image.h"
#include "../include/constant.h"
#include "../include/game.h"
#include "../include/constant.h"
#include "../include/bomb_list.h"
#include "../include/bomb.h"


struct s_list {
	t_cell head;
	int size;
};

struct s_cell {
	t_bomb bomb;
	t_cell next;
	t_cell previous;
};

t_list
bomb_list_init(t_bomb bomb)
{
	t_list list = malloc(sizeof(*list));
	t_cell cell=malloc(sizeof(*cell));

	assert(list);
	assert(cell);

	cell->bomb=bomb;
	cell->next = NULL;
	cell->previous = NULL;

	list->head = cell;

	return list;
}


t_list
bomb_list_add(t_list list, t_bomb bomb){
	assert(list);

	t_cell cell=malloc(sizeof(*cell));
	assert(cell);

	cell->bomb=bomb;
	cell->next=list->head;
	cell->previous=NULL;
	list->head->previous=cell;
	list->head=cell;
	list->size +=1;

	return list;
}


t_cell
bomb_list_get_head(t_list list)
{
	assert(list);
	return list->head;
}

int
bomb_list_get_size(t_list list)
{
	assert(list);
	return list->size;
}


t_cell
bomb_list_get_next_cell(t_cell cell)
{
	assert(cell);
	return cell->next;
}


t_cell
bomb_list_get_previous_cell(t_cell cell)
{
	assert(cell);
	return cell->previous;
}


void
bomb_list_display(t_list list, 	SDL_Surface *screen, t_map map, t_player player,t_list monster_list,t_monster monster){
	assert(list);

	t_cell cell = bomb_list_get_head(list);
	while( cell->next){
		if(bomb_display(cell->bomb, screen, map, player,monster_list,monster) == 0)
			bomb_list_delete(list, cell->bomb);
		cell = cell->next;
	}
}


t_list
bomb_list_delete(t_list list, t_bomb bomb)
{
	assert(list);
	if(list){
		t_cell key=list->head;
		int found=0;

		while (key->bomb != NULL && !found) {
			if(key->bomb==bomb) {

				if(key->previous==NULL) {
					list->head=bomb_list_get_next_cell(key);
					list->head->previous=NULL;
				}

				else if(key->next==NULL) {
					key->previous->next=NULL;
				}

				else {
					key->previous->next=key->next;
					key->next->previous=key->previous;
				}
				free(key);
				found=1;
			}
			else key=bomb_list_get_next_cell(key);
		}
	}
	return list;
}

void bomb_list_adapte_time(t_list bomb_list, Uint32 time){
	assert(bomb_list);
	t_bomb key_data;

	t_cell key = bomb_list_get_head(bomb_list);

	while(bomb_list_get_next_cell(key)){
		key_data = key->bomb;

		bomb_set_time(key_data, time + bomb_get_time(key_data));
		key = bomb_list_get_next_cell(key);
	}
}


